package com.galaxy.stock.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.galaxy.stock.dao.DBInfoDao;
import com.galaxy.stock.domain.TTableBackupConfig;
import com.galaxy.stock.mapper.TTableBackupConfigMapper;
import com.galaxy.stock.service.IDataBackupService;

/**
 * 股票代码Service业务层处理
 * 
 * @author lucifer
 * @date 2020-10-18
 */
@Service
public class DataBackupServiceImpl implements IDataBackupService {
    private static final Logger log = LoggerFactory.getLogger(DataBackupServiceImpl.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DBInfoDao dbInfoDao;
    @Autowired
    private TTableBackupConfigMapper tTableBackupConfigMapper;

    @Override
    @Transactional
    public void backup() {
        TTableBackupConfig queryConditionObj = new TTableBackupConfig();
        queryConditionObj.setStatus(0);
        List<TTableBackupConfig> list = tTableBackupConfigMapper.selectTTableBackupConfigList(queryConditionObj);

        for (TTableBackupConfig table : list) {
            String originTable = table.getOriginTable();
            String targetTable = table.getTargetTable();
            List<String> columnList = dbInfoDao.getDbColumnNames(originTable);
            String columnsStr = StringUtils.join(columnList, ",\n");
            String bakDate = DateUtils.dateTime();
            String backupSql = "insert into " + targetTable + "(bak_date," + columnsStr + ") select '" + bakDate + "',"+ columnsStr + " from " + originTable;

            log.info("backup:{} Sql: {}---------------", originTable, backupSql);
            int rownum = jdbcTemplate.update(backupSql);
            log.info("backup:{} result: {}---------------", originTable, rownum);
        }

        // int num = 1/0; //放开测试事务。预期结果为添加失败，库中无数据。测试结果与预期一致
    }

}
